//
//  RepairNewController.m
//  智慧小区
//
//  Created by lab603 on 15/7/1.
//  Copyright (c) 2015年 Dreamsoul. All rights reserved.
//

#import "RepairNewController.h"
#import "PPMeTextView.h"
#import "ActionSheetDatePicker.h"
#import "ActionSheetStringPicker.h"
#import "APIClient.h"
#import "MBProgressHUD+MJ.h"
#import "PECropViewController.h"
#import "PPHttpTool.h"
#import "EGOCache.h"
#import "UserInfo.h"
#import <AVFoundation/AVFoundation.h>
typedef enum {
    WaterRepair,
    ElectricRepair,
    DoorRepair,
    CleanService,
    Other
}repairType;
#define TopPadding 10
#define LeftPadding 15
#define pictureWH (ScreenWidth-4*LeftPadding)/3
#define Cache_UserInfoKey @"UserInfoCache"
@interface RepairNewController ()<UITextViewDelegate,UIActionSheetDelegate,UINavigationControllerDelegate, UIImagePickerControllerDelegate,PECropViewControllerDelegate>
//顶部背景
//scrollView
@property (nonatomic,weak)UIScrollView *scrollView;

@property (nonatomic,weak)UIImageView *topBackground;

//手机号码View
@property (nonatomic,weak)UIView *phoneView;
//手机号码Label
@property (nonatomic,weak)UILabel *phoneLabel;
//手机号码textField
@property (nonatomic,weak)UITextField *phoneField;

//报修时间View
@property (nonatomic,weak)UIView *timeView;
//报修时间Label
@property (nonatomic,weak)UILabel *timeLabel;
//选择时间label
@property (nonatomic,weak)UILabel *chooseTime;
//小剪头
@property (nonatomic,weak)UIImageView *timeArrowView;

//类型View
@property (nonatomic,weak)UIView *repairTypeView;
//类型Label
@property (nonatomic,weak)UILabel *repairTypeLabel;
//选择label
@property (nonatomic,weak)UILabel *chooseType;
//小剪头
@property (nonatomic,weak)UIImageView *typeArrowView;

//自定义TextView
@property (nonatomic,weak)PPMeTextView *defineTextView;

//底部视图
@property (nonatomic,weak)UIImageView *bottomView;
//语音按钮
@property (nonatomic,weak)UIButton *voiceBtn;
//语音播放按钮
@property (nonatomic,weak)UIButton *voicePlayBtn;

//图片1
@property (nonatomic,weak)UIImageView *pictureOne;
//图片2
@property (nonatomic,weak)UIImageView *pictureTwo;
//图片3
@property (nonatomic,weak)UIImageView *pictureThree;

//提交按钮
@property (nonatomic,weak)UIButton *commitBtn;

//存放报修类型的数组
@property (nonatomic,strong)NSArray *repairTypeArray;
//点击了第几张图片的标志
@property (nonatomic,assign)int pictureTag;
//选择的时间
@property (nonatomic,copy)NSString *timeString;
//报修种类的标志
@property (nonatomic,assign)int repairType;

//语音文件名
@property (nonatomic,copy)NSString *playName;
//录音文件设置字典
@property (nonatomic,strong)NSDictionary *recorderSettingsDict;
//图片组
@property (nonatomic,strong)NSMutableArray *volumImages;
//录音器
@property (nonatomic,strong)AVAudioRecorder *recorder;
//播放器
@property (nonatomic,strong)AVAudioPlayer *player;
@property (nonatomic,assign)double lowPassResults;
//语音背景
@property (nonatomic,weak)UIImageView *soundImageView;
//语音背景一
@property (nonatomic,weak)UIImageView *soundRecordImageView;
//语音背景二
@property (nonatomic,weak)UIImageView *soundLodingImageView;
//定时器
@property (nonatomic,strong)NSTimer *timer;
//记录是否有语音文件
@property (nonatomic,assign)BOOL isVoiceRecord;
@end

@implementation RepairNewController
- (NSArray *)repairTypeArray{
    if (_repairTypeArray==nil) {
        _repairTypeArray = @[@"给排水维修", @"室内电器", @"门窗", @"保洁", @"其他"];
    }
    return _repairTypeArray;
}
- (id)init{
    if (self=[super init]) {
        self.title = @"添加报修";
        self.view.backgroundColor = APP_BACK_COLOR;
    }
    return self;
}
- (void)viewDidLoad {
    //避免在ios7后出现导航栏遮挡视图
    if (iOS7) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
    [super viewDidLoad];
    //初始化子控件
    [self initSubView];
    //初始化语音
    [self initVoice];
    //初始化pictureTag
    self.pictureTag = 0;
    //初始化repairType
    self.repairType = 999;
}
/**
 *  初始化语音
 */
- (void)initVoice{
    if (iOS7) {
        //7.0第一次运行会提示，是否允许使用麦克风
        AVAudioSession *session = [AVAudioSession sharedInstance];
        NSError *sessionError;
        //AVAudioSessionCategoryPlayAndRecord用于录音和播放
        [session setCategory:AVAudioSessionCategoryPlayAndRecord error:&sessionError];
        if(session == nil)
            NSLog(@"Error creating session: %@", [sessionError description]);
        else
            [session setActive:YES error:nil];
    }
    NSString *docDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    _playName = [NSString stringWithFormat:@"%@/_Repair.aac",docDir];
    //录音设置
    _recorderSettingsDict =[[NSDictionary alloc] initWithObjectsAndKeys:
                           [NSNumber numberWithInt:kAudioFormatMPEG4AAC],AVFormatIDKey,
                           [NSNumber numberWithInt:1000.0],AVSampleRateKey,
                           [NSNumber numberWithInt:2],AVNumberOfChannelsKey,
                           [NSNumber numberWithInt:8],AVLinearPCMBitDepthKey,
                           [NSNumber numberWithBool:NO],AVLinearPCMIsBigEndianKey,
                           [NSNumber numberWithBool:NO],AVLinearPCMIsFloatKey,
                           nil];
    //音量图片数组
    _volumImages = [[NSMutableArray alloc]initWithObjects:@"RecordingSignal001",@"RecordingSignal002",@"RecordingSignal003",
                   @"RecordingSignal004", @"RecordingSignal005",@"RecordingSignal006",
                   @"RecordingSignal007",@"RecordingSignal008",nil];
    self.isVoiceRecord = NO;

}
/**
 *  初始化子控件
 */
- (void)initSubView{
    //scrollView
    UIScrollView *scrollView = [[UIScrollView alloc] init];
    [self.view addSubview:scrollView];
    self.scrollView = scrollView;
    
    //顶部背景
    UIImageView *topBackground = [[UIImageView alloc] init];
    topBackground.backgroundColor = [UIColor whiteColor];
    topBackground.userInteractionEnabled = YES;
    [topBackground addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hidenKeyboard)]];
    [self.scrollView addSubview:topBackground];
    self.topBackground = topBackground;
    
    //电话View
    UIView *phoneView=[[UIView alloc]init];
    phoneView.backgroundColor=[UIColor whiteColor];
    phoneView.layer.borderWidth = 0.5;
    phoneView.layer.borderColor = [APP_HINT_COLOR CGColor];
    [phoneView.layer setCornerRadius:CORNER_RADIUS_5];
    [self.topBackground addSubview:phoneView];
    self.phoneView = phoneView;
    //电话label
    UILabel *phoneLabel = [[UILabel alloc] init];
    phoneLabel.textColor=APP_WORD_COLOR_1;
    phoneLabel.text=@"手机号码";
    [phoneLabel setFont:[UIFont systemFontOfSize:14.4]];
    [phoneLabel sizeToFit];
    [self.phoneView addSubview: phoneLabel];
    self.phoneLabel = phoneLabel;
    //电话field
    UITextField *phoneField = [[UITextField alloc] init];
    phoneField.placeholder = @"请输入您的手机号码";
    phoneField.textColor = RGBACOLOR(86,84,84,1);
    phoneField.returnKeyType = UIReturnKeyDone;
    phoneField.font = [UIFont systemFontOfSize:16.0];
    phoneField.enablesReturnKeyAutomatically = YES;
    phoneField.clearButtonMode = UITextFieldViewModeAlways;
    [self.phoneView addSubview:phoneField];
    self.phoneField = phoneField;
    
    //报修时间View
    UIView *timeView=[[UIView alloc]init];
    timeView.backgroundColor=[UIColor whiteColor];
    timeView.layer.borderWidth = 0.5;
    timeView.layer.borderColor = [[UIColor lightGrayColor] CGColor];
    [timeView.layer setCornerRadius:CORNER_RADIUS_5];
    [self.topBackground addSubview:timeView];
    self.timeView = timeView;
    //时间Label
    UILabel *timeLabel = [[UILabel alloc] init];
    timeLabel.textColor=APP_WORD_COLOR_1;
    timeLabel.text=@"预约时间";
    [timeLabel setFont:[UIFont systemFontOfSize:14.4]];
    [timeLabel sizeToFit];
    [self.timeView addSubview: timeLabel];
    self.timeLabel = timeLabel;
    //选择label
    UILabel *chooseTime = [[UILabel alloc] init];
    chooseTime.textColor=APP_THEME_COLOR;
    chooseTime.text=@"请选择预约时间(点我)";
    chooseTime.tag = 0;
    [chooseTime setFont:[UIFont systemFontOfSize:16.0]];
    [chooseTime sizeToFit];
    //添加点击手势
    chooseTime.userInteractionEnabled = YES;
    [chooseTime addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(choose:)]];
    [self.timeView addSubview: chooseTime];
    self.chooseTime = chooseTime;
    //小剪头
    UIImageView *timeArrowView = [[UIImageView alloc] init];
    timeArrowView.image = [UIImage imageNamed:@"arrows_down_icon"];
    [self.timeView addSubview:timeArrowView];
    self.timeArrowView = timeArrowView;
    
    //报修类型View
    UIView *repairTypeView=[[UIView alloc]init];
    repairTypeView.backgroundColor=[UIColor whiteColor];
    repairTypeView.layer.borderWidth = 0.5;
    repairTypeView.layer.borderColor = [[UIColor lightGrayColor] CGColor];
    [repairTypeView.layer setCornerRadius:CORNER_RADIUS_5];
    [self.topBackground addSubview:repairTypeView];
    self.repairTypeView = repairTypeView;
    //时间Label
    UILabel *repairTypeLabel = [[UILabel alloc] init];
    repairTypeLabel.textColor=APP_WORD_COLOR_1;
    repairTypeLabel.text=@"报修类型";
    [repairTypeLabel setFont:[UIFont systemFontOfSize:14.4]];
    [repairTypeLabel sizeToFit];
    [self.repairTypeView addSubview: repairTypeLabel];
    self.repairTypeLabel = repairTypeLabel;
    //选择label
    UILabel *chooseType = [[UILabel alloc] init];
    chooseType.textColor=APP_THEME_COLOR;
    chooseType.text=@"请选择报修类型(点我)";
    chooseType.tag = 1;
    [chooseType setFont:[UIFont systemFontOfSize:16.0]];
    [chooseType sizeToFit];
    //添加点击手势
    chooseType.userInteractionEnabled = YES;
    [chooseType addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(choose:)]];
    [self.repairTypeView addSubview: chooseType];
    self.chooseType = chooseType;
    //小剪头
    UIImageView *typeArrowView = [[UIImageView alloc] init];
    typeArrowView.image = [UIImage imageNamed:@"arrows_down_icon"];
    [self.repairTypeView addSubview:typeArrowView];
    self.typeArrowView = typeArrowView;

    //自定义textView
    PPMeTextView *defineTextView = [[PPMeTextView alloc] init];
    defineTextView.font = [UIFont systemFontOfSize:16.0];
    defineTextView.frame = CGRectMake(0, 10, self.view.bounds.size.width, 40);
    defineTextView.alwaysBounceVertical = YES;
    defineTextView.delegate = self;
    defineTextView.placeholder = @"请填写报修描述(可不填)";
    defineTextView.layer.borderWidth = 0.5;
    defineTextView.layer.borderColor = [APP_HINT_COLOR CGColor];
    [defineTextView.layer setCornerRadius:CORNER_RADIUS_5];
    [self.topBackground addSubview:defineTextView];
    self.defineTextView = defineTextView;
    
    //底部视图
    UIImageView *bottomView = [[UIImageView alloc] init];
    bottomView.backgroundColor = [UIColor whiteColor];
    bottomView.userInteractionEnabled = YES;
    [bottomView addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(hidenKeyboard)]];
    [self.scrollView addSubview:bottomView];
    self.bottomView = bottomView;
    //语音按钮
    UIButton *voiceBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [voiceBtn setTitleColor:APP_THEME_COLOR forState:UIControlStateNormal];
    [voiceBtn setTitle:@"按我说话" forState:UIControlStateNormal];
    voiceBtn.layer.borderWidth = 1;
    voiceBtn.layer.borderColor = [[UIColor lightGrayColor] CGColor];
    [voiceBtn.layer setCornerRadius:CORNER_RADIUS_5];
    voiceBtn.clipsToBounds = YES;
    voiceBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    [voiceBtn setBackgroundImage:[UIImage resizedImageWithName:@"ItemBackground"] forState:UIControlStateNormal];
    [voiceBtn addTarget:self action:@selector(startRecord) forControlEvents:UIControlEventTouchDown];
    [voiceBtn addTarget:self action:@selector(stopRecord) forControlEvents:UIControlEventTouchUpInside];
    self.voiceBtn = voiceBtn;
    [self.bottomView addSubview:voiceBtn];
    
    //语音播放按钮
    UIButton *voicePlayBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [voicePlayBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    voicePlayBtn.titleLabel.font = [UIFont systemFontOfSize:14];
    [voicePlayBtn setTitle:@"语音播放" forState:UIControlStateNormal];
    voicePlayBtn.backgroundColor = APP_THEME_COLOR;
    [voicePlayBtn addTarget:self action:@selector(voiceBtnPlay) forControlEvents:UIControlEventTouchUpInside];
    voicePlayBtn.layer.cornerRadius = CORNER_RADIUS_5;
    voicePlayBtn.clipsToBounds = YES;
    [self.bottomView addSubview: voicePlayBtn];
    self.voicePlayBtn = voicePlayBtn;
    //默认隐藏
    self.voicePlayBtn.hidden = YES;
    
    //语音背景图
    UIImageView *soundImageView = [[UIImageView alloc] init];
    soundImageView.backgroundColor = [UIColor blackColor];
    soundImageView.alpha = 0.6;
    [self.scrollView addSubview:soundImageView];
    self.soundImageView = soundImageView;
    //默认隐藏
    soundImageView.hidden = YES;
    
    //语音背景图一
    UIImageView *soundRecordImageView = [[UIImageView alloc] init];
    soundRecordImageView.image = [UIImage imageNamed:@"RecordingBkg"];
    [self.soundImageView addSubview:soundRecordImageView];
    self.soundRecordImageView = soundRecordImageView;
    
    //语音动态图
    UIImageView *soundLodingImageView = [[UIImageView alloc] init];
    [self.soundImageView addSubview:soundLodingImageView];
    self.soundLodingImageView = soundLodingImageView;
    
    //图片1
    UIImageView *pictureOne = [[UIImageView alloc] init];
    pictureOne.userInteractionEnabled = YES;
    pictureOne.image =[UIImage imageNamed:@"comment_picture"];
    pictureOne.tag = 1;
    [pictureOne addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(pictureTapped:)]];
    [self.bottomView addSubview:pictureOne];
    self.pictureOne = pictureOne;
    //图片2
    UIImageView *pictureTwo = [[UIImageView alloc] init];
    pictureTwo.userInteractionEnabled = YES;
    pictureTwo.image =[UIImage imageNamed:@"comment_picture"];
    [pictureTwo addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(pictureTapped:)]];
    pictureTwo.hidden = YES;
    pictureTwo.tag = 2;
    [self.bottomView addSubview:pictureTwo];
    self.pictureTwo = pictureTwo;
    //图片3
    UIImageView *pictureThree = [[UIImageView alloc] init];
    pictureThree.userInteractionEnabled = YES;
    pictureThree.image =[UIImage imageNamed:@"comment_picture"];
    [pictureThree addGestureRecognizer:[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(pictureTapped:)]];
    pictureThree.hidden = YES;
    pictureThree.tag = 3;
    [self.bottomView addSubview:pictureThree];
    self.pictureThree = pictureThree;
    
    //提交按钮
    UIButton *commitBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [commitBtn setTitleColor:APP_THEME_COLOR forState:UIControlStateNormal];
    [commitBtn setTitle:@"提交" forState:UIControlStateNormal];
    commitBtn.backgroundColor = [UIColor whiteColor];
    commitBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    [commitBtn addTarget:self action:@selector(commitTapped) forControlEvents:UIControlEventTouchUpInside];
    [self.scrollView addSubview: commitBtn];
    self.commitBtn = commitBtn;
    
    //设置子控件属性
    [self setSubView];
}
/**
 *  设置子控件属性
 */
- (void)setSubView{
    //scrollview
    _scrollView.frame = self.view.bounds;
    //语音背景图
    CGSize soundImageViewSize = (CGSize){160,160};
    CGFloat soundImageViewX = (ScreenWidth - soundImageViewSize.width)*0.5;
    CGFloat soundImageViewY = 120;
    _soundImageView.frame = (CGRect){{soundImageViewX,soundImageViewY},soundImageViewSize};
    
    //语音背景图一
    CGSize soundRecordImageViewSize = (CGSize){36,80};
    CGFloat soundRecordImageViewX = 44;
    CGFloat soundRecordImageViewY = 30;
    _soundRecordImageView.frame = (CGRect){{soundRecordImageViewX,soundRecordImageViewY},soundRecordImageViewSize};
    
    //语音背景二
    CGSize soundLodingImageViewSize = (CGSize){18,60};
    CGFloat soundLodingImageViewX = 99;
    CGFloat soundLodingImageViewY = 49;
    _soundLodingImageView.frame = (CGRect){{soundLodingImageViewX,soundLodingImageViewY},soundLodingImageViewSize};
    
    CGFloat VHeight = 35;
    //顶部背景
    CGFloat topBackgroundX = 0;
    CGFloat topBackgroundY = LeftPadding;
    CGFloat topBackgroundW = ScreenWidth;
    //高度待定
    CGFloat topBackgroundH = 0;
    //手机View
    CGFloat phoneViewX = LeftPadding;
    CGFloat phoneViewY = TopPadding;
    CGFloat phoneViewW = ScreenWidth-2*LeftPadding;
    CGFloat phoneViewH = VHeight;
    _phoneView.frame = CGRectMake(phoneViewX, phoneViewY, phoneViewW, phoneViewH);
    //手机Label
    CGFloat phoneLabelX = TopPadding;
    CGFloat phoneLabelY = TopPadding;
    _phoneLabel.frame = (CGRect){{phoneLabelX,phoneLabelY},self.phoneLabel.bounds.size};
    //手机TextField
    CGFloat phoneFieldX = CGRectGetMaxX(_phoneLabel.frame)+TopPadding;
    CGFloat phoneFieldY = 0;
    CGFloat phoneFieldW = phoneViewW - phoneViewX - LeftPadding*2;
    CGFloat phoneFieldH = VHeight;
    _phoneField.frame = CGRectMake(phoneFieldX, phoneFieldY, phoneFieldW, phoneFieldH);
    
    //报修时间view
    CGFloat timeViewX = LeftPadding;
    CGFloat timeViewY = CGRectGetMaxY(_phoneView.frame)+TopPadding;
    CGFloat timeViewW = ScreenWidth - LeftPadding*2;
    CGFloat timeViewH = VHeight;
    _timeView.frame = CGRectMake(timeViewX, timeViewY, timeViewW, timeViewH);
    //报修时间Label
    CGFloat timeLabelX = TopPadding;
    CGFloat timeLabelY = TopPadding;
    _timeLabel.frame = (CGRect){{timeLabelX,timeLabelY},self.timeLabel.bounds.size};
    //选择报修
    CGFloat chooseTimeX = 80;
    CGFloat chooseTimeY = 0;
    CGFloat chooseTimeW = 180;
    CGFloat chooseTimeH = VHeight;
    _chooseTime.frame = (CGRect)CGRectMake(chooseTimeX, chooseTimeY, chooseTimeW, chooseTimeH);
    //小箭头
    CGSize timeArrowViewSize = CGSizeMake(20, 20);
    CGFloat timeArrowViewX = timeViewW - LeftPadding - timeArrowViewSize.width;
    CGFloat timeArrowViewY = (VHeight - timeArrowViewSize.height)*0.5;
    _timeArrowView.frame = (CGRect){{timeArrowViewX,timeArrowViewY},timeArrowViewSize};
    
    //类别view
    CGFloat repairTypeViewX = LeftPadding;
    CGFloat repairTypeViewY = CGRectGetMaxY(_timeView.frame)+TopPadding;
    CGFloat repairTypeViewW = ScreenWidth - LeftPadding*2;
    CGFloat repairTypeViewH = VHeight;
    _repairTypeView.frame = CGRectMake(repairTypeViewX, repairTypeViewY, repairTypeViewW, repairTypeViewH);
    //类别Label
    CGFloat repairTypeLabelX = TopPadding;
    CGFloat repairTypeLabelY = TopPadding;
    _repairTypeLabel.frame = (CGRect){{repairTypeLabelX,repairTypeLabelY},self.repairTypeLabel.bounds.size};
    //选择类别
    CGFloat chooseTypeX = 80;
    CGFloat chooseTypeY = 0;
    CGFloat chooseTypeW = 180;
    CGFloat chooseTypeH = VHeight;
    _chooseType.frame = (CGRect)CGRectMake(chooseTypeX, chooseTypeY, chooseTypeW, chooseTypeH);
    //小箭头
    CGSize typeArrowViewSize = CGSizeMake(20, 20);
    CGFloat typeArrowViewX = repairTypeViewW - LeftPadding - typeArrowViewSize.width;
    CGFloat typeArrowViewY = (VHeight - typeArrowViewSize.height)*0.5;
    _typeArrowView.frame = (CGRect){{typeArrowViewX,typeArrowViewY},typeArrowViewSize};
    
    //自定义textView
    CGFloat defineTextViewX = repairTypeViewX;
    CGFloat defineTextViewY = CGRectGetMaxY(_repairTypeView.frame)+TopPadding;
    CGFloat defineTextViewW = ScreenWidth - 2*LeftPadding;
    CGFloat defineTextViewH = 80;
    _defineTextView.frame = CGRectMake(defineTextViewX, defineTextViewY, defineTextViewW, defineTextViewH);
    topBackgroundH = CGRectGetMaxY(_defineTextView.frame)+TopPadding;
    _topBackground.frame = CGRectMake(topBackgroundX, topBackgroundY, topBackgroundW, topBackgroundH);
    
    //bottom背景
    CGFloat bottomViewX = 0;
    CGFloat bottomViewY = CGRectGetMaxY(_topBackground.frame)+LeftPadding;
    CGFloat bottomViewW = ScreenWidth;
    //高度待定
    CGFloat bottomViewH = 0;
    
    //语音按钮
    CGFloat voiceBtnX = LeftPadding;
    CGFloat voiceBtnY = TopPadding;
    CGFloat voiceBtnW = pictureWH;
    CGFloat voiceBtnH = 35;
    _voiceBtn.frame = CGRectMake(voiceBtnX, voiceBtnY, voiceBtnW, voiceBtnH);
    
    //语音播放按钮
    CGFloat voicePlayBtnX = CGRectGetMaxX(_voiceBtn.frame)+LeftPadding;
    CGFloat voicePlayBtnY = voiceBtnY;
    CGSize  voicePlayBtnSize = (CGSize){90,35};
    _voicePlayBtn.frame = (CGRect){{voicePlayBtnX,voicePlayBtnY},voicePlayBtnSize};
    
    //图片一
    CGFloat pictureOneX = LeftPadding;
    CGFloat pictureOneY = CGRectGetMaxY(_voiceBtn.frame)+TopPadding;
    CGSize pictureOneSize = (CGSize){pictureWH,pictureWH};
    _pictureOne.frame = (CGRect){{pictureOneX,pictureOneY},pictureOneSize};
    //图片二
    CGFloat pictureTwoX = CGRectGetMaxX(_pictureOne.frame)+LeftPadding;
    CGFloat pictureTwoY = pictureOneY;
    CGSize pictureTwoSize = (CGSize){pictureWH,pictureWH};
    _pictureTwo.frame = (CGRect){{pictureTwoX,pictureTwoY},pictureTwoSize};
    //图片三
    CGFloat pictureThreeX = CGRectGetMaxX(_pictureTwo.frame)+LeftPadding;
    CGFloat pictureThreeY = pictureTwoY;
    CGSize pictureThreeSize = (CGSize){pictureWH,pictureWH};
    _pictureThree.frame = (CGRect){{pictureThreeX,pictureThreeY},pictureThreeSize};
    bottomViewH = CGRectGetMaxY(_pictureOne.frame)+TopPadding;
    _bottomView.frame = CGRectMake(bottomViewX, bottomViewY, bottomViewW, bottomViewH);
    
    //提交按钮
    CGFloat commitBtnX = 0;
    CGFloat commitBtnY = CGRectGetMaxY(_bottomView.frame)+LeftPadding;
    CGFloat commitBtnW = ScreenWidth;
    CGFloat commitBtnH = 40;
    _commitBtn.frame = CGRectMake(commitBtnX, commitBtnY, commitBtnW, commitBtnH);
    
    //scrollView的contentSize
    _scrollView.contentSize = (CGSize){ScreenWidth,CGRectGetMaxY(_commitBtn.frame)+LeftPadding+STATUSBAR_HEIGHT+NAVIGATION_HEIGHT};
}
/**
 *  开始播放语音
 */
- (void)voiceBtnPlay{
    NSError *playerError;
    //播放
    _player = nil;
    _player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL URLWithString:_playName] error:&playerError];
    
    if (_player == nil)
    {
        NSLog(@"ERror creating player: %@", [playerError description]);
    }else{
        //使用扬声器
        UInt32 doChangeDefaultRoute = 1;
        AudioSessionSetProperty (kAudioSessionProperty_OverrideCategoryDefaultToSpeaker, sizeof (doChangeDefaultRoute), &doChangeDefaultRoute);
        [_player play];
    }
}
/**
 *  停止录音
 */
- (void)stopRecord{
    //隐藏语音背景
    self.soundImageView.hidden = YES;
    //显示播放按钮
    self.voicePlayBtn.hidden = NO;
    //录音停止
    [_recorder stop];
    _recorder = nil;
    //结束定时器
    [_timer invalidate];
    _timer = nil;
    //图片重置
    _soundLodingImageView.image = [UIImage imageNamed:[_volumImages objectAtIndex:0]];
    self.isVoiceRecord = YES;
}
/**
 *  开始录音
 */
- (void)startRecord{
    
    //显示语音背景
    self.soundImageView.hidden = NO;
    //按下录音
    if ([self canRecord]) {
        
        NSError *error = nil;
        //必须真机上测试,模拟器上可能会崩溃
        _recorder = [[AVAudioRecorder alloc] initWithURL:[NSURL URLWithString:_playName] settings:_recorderSettingsDict error:&error];
        
        if (_recorder) {
            _recorder.meteringEnabled = YES;
            [_recorder prepareToRecord];
            [_recorder record];
            
            //启动定时器
            _timer = [NSTimer scheduledTimerWithTimeInterval:0.1 target:self selector:@selector(levelTimer:) userInfo:nil repeats:YES];
            
        } else
        {
            int errorCode = CFSwapInt32HostToBig ([error code]);
            NSLog(@"Error: %@ [%4.4s])" , [error localizedDescription], (char*)&errorCode);
            
        }
    }

}
/**
 *  点击了提交按钮
 */
- (void)commitTapped{
    //判断提交条件
    if ([self.phoneField.text isEqualToString:@""]) {
        [MBProgressHUD showError:@"请输入手机号"];
        return;
    }
    if (self.timeString==nil) {
        [MBProgressHUD showError:@"请选择报修时间"];
        return;
    }
    if (self.repairType ==999) {
        [MBProgressHUD showError:@"请选择报修类型"];
        return;
    }
    if (self.pictureTag==0&&[self.defineTextView.text isEqualToString:@""]) {
        [MBProgressHUD showError:@"请描述您的报修情况"];
        return;
    }
    NSString *urlString = [APIClient relativePathForNewRepair];
    UserInfo *userInfo = (UserInfo *)[[EGOCache globalCache] objectForKey:Cache_UserInfoKey];
    //封装请求参数
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    params[@"tel"] = self.phoneField.text;
    params[@"timeOne"] = self.timeString;
    params[@"type"] = @(self.repairType);
    params[@"text"] = self.defineTextView.text;
    params[@"room"] = userInfo.room;
    params[@"contact"] = userInfo.name;
    NSMutableArray *pictureArray = [NSMutableArray array];
    if (self.pictureTag==1) {
        [pictureArray addObject:UIImageJPEGRepresentation(self.pictureOne.image,0.4)];
    }else if (self.pictureTag==2){
        [pictureArray addObject:UIImageJPEGRepresentation(self.pictureOne.image,0.4)];
        [pictureArray addObject:UIImageJPEGRepresentation(self.pictureTwo.image,0.4)];
    }else if (self.pictureTag==3){
        [pictureArray addObject:UIImageJPEGRepresentation(self.pictureOne.image,0.4)];
        [pictureArray addObject:UIImageJPEGRepresentation(self.pictureTwo.image,0.4)];
        [pictureArray addObject:UIImageJPEGRepresentation(self.pictureThree.image,0.4)];
    }
    //封装文件参数
    NSMutableArray *formDataArray = [NSMutableArray array];
    for (int i=0; i<pictureArray.count; i++) {
        IWFormData *formData = [[IWFormData alloc] init];
        formData.data = pictureArray[i];
        switch (i) {
            case 0:{
                formData.name = @"pictureOne";
            }
                break;
            case 1:{
                formData.name = @"pictureTwo";
            }
                break;
            case 2:{
                formData.name = @"pictureThree";
            }
                break;
            default:
                break;
        }
        formData.mimeType = @"image/jpeg";
        formData.filename = @"";
        [formDataArray addObject:formData];
    }
    NSData *voiceData = nil;
    if (self.isVoiceRecord) {
        NSFileHandle *fileHandle = [NSFileHandle fileHandleForReadingAtPath:self.playName];
        voiceData = [fileHandle readDataToEndOfFile];
        IWFormData *formData = [[IWFormData alloc] init];
        formData.data = voiceData;
        formData.name = @"voice";
        formData.mimeType = @"audio/mpeg3";
        formData.filename = @"";
        [formDataArray addObject:formData];
    }
    [PPHttpTool postWithURL:urlString params:params formDataArray:formDataArray success:^(id json) {
        IWLog(@"%@",json);
        if ([json[@"resultCode"] isEqual:@1]) {
            [MBProgressHUD showSuccess:@"提交成功"];
            [self.navigationController popViewControllerAnimated:YES];
        }else{
            [MBProgressHUD showError:@"提交失败"];
        }
    } failure:^(NSError *error) {
        [MBProgressHUD showError:@"提交失败"];
    }];
}
/**
 *  选择图片
 */
- (void)pictureTapped:(UITapGestureRecognizer*)tap{
    switch (tap.view.tag) {
        case 1:{
            self.pictureTag = 1;
        }
            break;
        case 2:{
            self.pictureTag = 2;
        }
            break;
        case 3:{
            self.pictureTag = 3;
        }
            break;
        default:
            break;
    }
    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                             delegate:self
                                                    cancelButtonTitle:@"取消"
                                               destructiveButtonTitle:@"拍照"
                                                    otherButtonTitles:@"用户相册", nil];
    [actionSheet showInView:self.view];
}
/**
 *  隐藏键盘
 */
- (void)hidenKeyboard{
    [self.view endEditing:YES];
}
/**
 *  点击了选择label
 */
- (void)choose:(UITapGestureRecognizer*)tap{
    [self.view endEditing:YES];
    switch (tap.view.tag) {
        case 0:{
            //创建时间pickerView
            //获得当前时间
            [ActionSheetDatePicker showPickerWithTitle:@"请选择报修时间" datePickerMode:UIDatePickerModeDateAndTime selectedDate:[NSDate date] doneBlock:^(ActionSheetDatePicker *picker, id selectedDate, id origin) {
                self.chooseTime.textColor = [UIColor blackColor];
                self.chooseTime.text = [self dealWithSelectedDate:selectedDate];
                self.timeString = self.chooseTime.text;
                } cancelBlock:^(ActionSheetDatePicker *picker) {
                
            } origin:self.view];
        }
            break;
        case 1:{
            //创建pickerView
            [ActionSheetStringPicker showPickerWithTitle:@"请选择报修类型" rows:self.repairTypeArray initialSelection:0 doneBlock:^(ActionSheetStringPicker *picker, NSInteger selectedIndex, id selectedValue) {
                IWLog(@"%ld,%@",(long)selectedIndex,selectedValue);
                self.repairType = (int)selectedIndex+1;
                self.chooseType.textColor = [UIColor blackColor];
                self.chooseType.text = selectedValue;
            } cancelBlock:^(ActionSheetStringPicker *picker) {
            } origin:self.view];

        }
        default:
            break;
    }
}
/**
 *  actionSheet的代理方法
 */
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    NSString *titile = [actionSheet buttonTitleAtIndex:buttonIndex];
    if ([titile isEqualToString:@"拍照"]) {
        [self openCamera];
    }else if([titile isEqualToString:@"用户相册"]){
        [self openPhotoLibrary];
    }
}
/**
 *  打开照相机
 */
- (void)openCamera{
    UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
    ipc.sourceType = UIImagePickerControllerSourceTypeCamera;
    ipc.delegate = self;
    [self presentViewController:ipc animated:YES completion:nil];
}
/**
 *  打开用户相册
 */
- (void)openPhotoLibrary{
    UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
    ipc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    ipc.delegate = self;
    [self presentViewController:ipc animated:YES completion:nil];
}
/**
 *  imagePickerController的代理方法
 */
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    // 1.销毁picker控制器
    [picker dismissViewControllerAnimated:YES completion:nil];
    // 2.取得图片
    UIImage *image = info[UIImagePickerControllerOriginalImage];
    // 3.截图
    PECropViewController *controller = [[PECropViewController alloc] init];
    controller.delegate = self;
    controller.image = image;
    controller.title = @"裁剪";
    controller.toolbarHidden = YES;
    [self.navigationController pushViewController:controller animated:YES];
    }
/**
 *  PEPhotoCrop的确定按钮代理
 */
- (void)cropViewController:(PECropViewController *)controller didFinishCroppingImage:(UIImage *)croppedImage{
    switch (self.pictureTag) {
        case 1:{
            self.pictureOne.image = croppedImage;
            self.pictureTwo.hidden = NO;
        }
            break;
        case 2:{
            self.pictureTwo.image = croppedImage;
            self.pictureThree.hidden = NO;
        }
            break;
        case 3:{
            self.pictureThree.image = croppedImage;
        }
            break;
        default:
            break;
    }
    [self.navigationController popViewControllerAnimated:YES];
}
/**
 *  PEPhotoCrop的取消按钮代理
 */
- (void)cropViewControllerDidCancel:(PECropViewController *)controller{
    [self.navigationController popViewControllerAnimated:YES];
}
/**
 *  对选择的时间进行处理
 */
- (NSString *)dealWithSelectedDate:(NSDate *)selectedDate{
    //解决时差问题
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate: selectedDate];
    NSDate *localDate = [selectedDate  dateByAddingTimeInterval: interval];
    //对日期进行处理
    NSString *timeString = [localDate description];
    int stringLength = (int)[timeString length];
    NSString *dealDateString = [timeString substringToIndex:stringLength-6];
    return dealDateString;
}
//判断是否允许使用麦克风7.0新增的方法requestRecordPermission
-(BOOL)canRecord
{
    __block BOOL bCanRecord = YES;
    if ([[[UIDevice currentDevice] systemVersion] compare:@"7.0"] != NSOrderedAscending)
    {
        AVAudioSession *audioSession = [AVAudioSession sharedInstance];
        if ([audioSession respondsToSelector:@selector(requestRecordPermission:)]) {
            [audioSession performSelector:@selector(requestRecordPermission:) withObject:^(BOOL granted) {
                if (granted) {
                    bCanRecord = YES;
                }
                else {
                    bCanRecord = NO;
                    dispatch_async(dispatch_get_main_queue(), ^{
                        [[[UIAlertView alloc] initWithTitle:nil
                                                    message:@"app需要访问您的麦克风。\n请启用麦克风-设置/隐私/麦克风"
                                                   delegate:nil
                                          cancelButtonTitle:@"关闭"
                                          otherButtonTitles:nil] show];
                    });
                }
            }];
        }
    }
    
    return bCanRecord;
}
-(void)levelTimer:(NSTimer*)timer
{
    //call to refresh meter values刷新平均和峰值功率,此计数是以对数刻度计量的,-160表示完全安静，0表示最大输入值
    [_recorder updateMeters];
    const double ALPHA = 0.05;
    double peakPowerForChannel = pow(10, (0.05 * [_recorder peakPowerForChannel:0]));
    _lowPassResults = ALPHA * peakPowerForChannel + (1.0 - ALPHA) * _lowPassResults;
    
    NSLog(@"Average input: %f Peak input: %f Low pass results: %f", [_recorder averagePowerForChannel:0], [_recorder peakPowerForChannel:0], _lowPassResults);
    
    if (_lowPassResults>=0.8) {
        _soundLodingImageView.image = [UIImage imageNamed:[_volumImages objectAtIndex:7]];
    }else if(_lowPassResults>=0.7){
        _soundLodingImageView.image = [UIImage imageNamed:[_volumImages objectAtIndex:6]];
    }else if(_lowPassResults>=0.6){
        _soundLodingImageView.image = [UIImage imageNamed:[_volumImages objectAtIndex:5]];
    }else if(_lowPassResults>=0.5){
        _soundLodingImageView.image = [UIImage imageNamed:[_volumImages objectAtIndex:4]];
    }else if(_lowPassResults>=0.4){
        _soundLodingImageView.image = [UIImage imageNamed:[_volumImages objectAtIndex:3]];
    }else if(_lowPassResults>=0.3){
        _soundLodingImageView.image = [UIImage imageNamed:[_volumImages objectAtIndex:2]];
    }else if(_lowPassResults>=0.2){
        _soundLodingImageView.image = [UIImage imageNamed:[_volumImages objectAtIndex:1]];
    }else if(_lowPassResults>=0.1){
        _soundLodingImageView.image = [UIImage imageNamed:[_volumImages objectAtIndex:0]];
    }else{
        _soundLodingImageView.image = [UIImage imageNamed:[_volumImages objectAtIndex:0]];
    }
    
}

@end
